package com.vip.pathbootstarter.anon;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.vip.pathbootstarter.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.net.URL;

/**
 * 反序列化
 */
public class PathFieldDeserializer extends JsonDeserializer<String> implements ContextualDeserializer {

    @Value("${path.prefix:''}")
    String configPrefix;

    private String prefix;

    @Override
    public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {
        String value = jsonParser.readValueAs(String.class); // 反序列化字符串字段
        if(StrUtil.isNotEmpty(value)){
            boolean httpUrl = isHttpUrl(value);
            if(httpUrl){
                if(StrUtil.isEmpty(prefix)){
                    prefix = configPrefix;
                }
                value = value.replaceAll(prefix,"");
            }
        }
        return value;
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext deserializationContext, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty != null) {
            PathField annotation = beanProperty.getAnnotation(PathField.class);
            prefix = annotation.prefix();
        }
        return this;
    }

    public static boolean isHttpUrl(String url) {
        try {
            URL u = new URL(url);
            return "http".equals(u.getProtocol());
        } catch (Exception e) {
            return false;
        }
    }

}
